package com.unbook.controller;

import com.unbook.entity.AdminUser;
import com.unbook.entity.ResponseVo;
import com.unbook.entity.params.AdminLoginParam;
import com.unbook.enums.EVerifyState;
import com.unbook.service.IAdminUserService;
import com.unbook.service.IVerifyService;
import com.unbook.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("/admin/user")
public class AdminUserController {
    @Autowired
    private IAdminUserService adminUserService;
    @Autowired
    private IVerifyService verifyService;
    @PostMapping("/login")
    public ResponseVo<AdminUser> login(@RequestBody AdminLoginParam param, HttpServletRequest request){
        EVerifyState state = verifyService.checkCode(request.getSession().getId(), param.getVerifyCode());
        if(state != EVerifyState.OK){
            return ResponseVo.custom(state.getCode(), state.getDesc());
        }
        AdminUser user = adminUserService.login(param);
        if(user != null){
            String token = JwtUtils.getToken(user.getId(),1, new HashMap<String, String>(){{
                put("name", user.getNickName());
            }});
            return ResponseVo.success(user, token);
        }
        else
            return ResponseVo.error("账号或密码错误");
    }
}
